package com.groupbuying.payconsumer.mq;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.serializer.SerializerFeature;
import com.groupbuying.payconsumer.connector.FinancialFegin;
import com.groupbuying.payconsumer.connector.OrderFeign;
import com.groupbuying.payconsumer.connector.SysconfigFeign;
import com.groupbuying.payconsumer.constants.BalancePayConstans;
import com.groupbuying.payconsumer.constants.PayInfoEnumConstants;
import com.groupbuying.payconsumer.dao.PayInfoDao;
import com.groupbuying.payconsumer.domain.PayInfoDO;
import com.groupbuying.payconsumer.domain.PayOrderRelDO;
import com.groupbuying.payconsumer.service.PayInfoService;
import com.groupbuying.payconsumer.service.PayOrderRelService;
import com.groupbuying.payconsumer.utils.NumberValidator;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * `余额支付主动查询逻辑处理类
 * @auther lisurilige
 * @date 2019/9/3
 */
@Component
public class BalancePayStateConfirm {
    Logger LOGGER = LoggerFactory.getLogger(BalancePayStateConfirm.class);

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private PayOrderRelService payOrderRelService;

    @Autowired
    private PayInfoDao payInfoDao;

    @Autowired
    private PayInfoService payInfoService;

    @Autowired
    private Producer producer;

    @Autowired
    private FinancialFegin financialFegin;

    /**
     *  余额支付主动查询支付信息
     * @param resultParam   查询参数
     * @return
     */
    public boolean dealResult(Map<String,Object> resultParam){

        String baseLog = "余额支付主动查询支付信息，";
        //1. 解析参数
        String dealNo = resultParam.get("key") == null ? "" : resultParam.get("key").toString();    //第三方订单号id

        //2. 判断是否为空
        if (StringUtils.isEmpty(dealNo)){
            LOGGER.error("{},调用信息，第三方单号不能为空",baseLog);
            return false;
        }
        LOGGER.info("{}支付结果主动查询开始 第三方交易单号：{}",baseLog,dealNo);

        //3. 获取订单信息
        PayOrderRelDO payOrderRelDO = payOrderRelService.getByOutTradeNo(dealNo);
        PayInfoDO payInfoDO = payInfoDao.get(payOrderRelDO.getId());

        if (payInfoDO == null){
            LOGGER.error("{}查询订单不存在，第三方单号：{}", baseLog,dealNo);
            return true;
        }

        if (payInfoDO.getPayBalance() == null){
            LOGGER.error("{}查询订单金额为空，第三方单号：{}", baseLog,dealNo);
            return true;
        }

        //4. 判断订单状态
        if (PayInfoEnumConstants.ENUM_PAYSTATE_SUCPAY.equals(payInfoDO.getPayState())){
            LOGGER.info("{}支付单已经完成交易流程:{}" ,baseLog,payInfoDO.getId());
            return true;
        }

        if (!PayInfoEnumConstants.ENUM_PAYSTATE_UNPAY.equals(payInfoDO.getPayState())) {
            LOGGER.info("{}支付单已经进行了其他操作:{}",baseLog,payInfoDO.getId());
            return true;
        }

        Map orderMap = null;

        try {
            //TODO 调用余额接口查询
            Map<String,Object> resultMap = financialFegin.balancePayQuery(dealNo);

            LOGGER.info("======接收参数，resultMap:{}", JSON.toJSONString(resultMap));
            String state = resultMap.get("state") == null ? null : resultMap.get("state").toString();
            String message = resultMap.get("message") == null ? null : resultMap.get("message").toString();
            String payMoney = resultMap.get("payMoney") == null ? null : resultMap.get("payMoney").toString();
            String orderNum = resultMap.get("orderNum") == null ? null : resultMap.get("orderNum").toString();

            //5. 判断返回是否有数据
            if (StringUtils.isEmpty(state)) {
                LOGGER.error("{}回执支付信息，成功标识为空，订单号：{}，code：{}，msg：{}",
                        baseLog, orderNum, state, message);
                return true;
            }

            if (StringUtils.isEmpty(orderNum)) {
                LOGGER.error("{}回执支付信息，第三方单号为空，订单号：{}，code：{}，msg：{}",
                        baseLog, orderNum, state, message);
                return true;
            }

            if (StringUtils.isEmpty(payMoney)) {
                LOGGER.error("{}回执支付信息，金额为空，订单号：{}，code：{}，msg：{}",
                        baseLog, orderNum, state, message);
                return true;
            }

            //判断金额是否合法
            if (!NumberValidator.isNumber(payMoney)) {
                LOGGER.error("{}回执支付交易金额，不是数字，第三方单号：{}，code：{}，msg：{}，payMoney：{}",
                        baseLog, orderNum, state, message, payMoney);
                return true;
            }

            //检查金额是否相等
            if (payInfoDO.getPayBalance().compareTo(new BigDecimal(payMoney)) != 0) {
                LOGGER.error("{}订单金额与回执支付信息，金额不匹配，订单号：{}，code：{}，msg：{}，订单金额:{},回执金额:{}",
                        baseLog, orderNum, state, message, payInfoDO.getPayBalance(), payMoney);
                return true;
            }

            //6. 判断返回交易状态是否成功(不是成功直接退出)
            if (BalancePayConstans.BALANCE_PAY_SUCCESS.equals(state)) {
                //查看订单是否为交易成功状态
                if (PayInfoEnumConstants.ENUM_PAYSTATE_SUCPAY.equals(payInfoDO.getPayState())) {
                    LOGGER.info("{}已经是交易成功状态，不做处理，第三方支付id：{}，code：{}，msg：{},订单金额:{}",
                            orderNum, state, message, payMoney);
                    return true;
                }
                payInfoDO.setPayState(PayInfoEnumConstants.ENUM_PAYSTATE_SUCPAY);
                payInfoDO.setGmtModified(new Date());
                payInfoService.update(payInfoDO);
            } else {
                LOGGER.error("{}，回执信息处理，交易状态为未成功，第三方单号：{}，code：{}，msg：{}",
                        baseLog, orderNum, state, message);
                return true;
            }

            //7.获取订单信息
            orderMap = orderFeign.getOrderForPay(payOrderRelDO.getOrderId());
        }catch (Exception e) {
            e.printStackTrace();
            return true;
        }
        //8.订单是否属于够样优店
//        boolean curNotify = orderMap.get("orderId").toString().substring(4, 7).equals("000");
        //9.商户优惠规则 是否未删除和已存在
//        if (curNotify) {
//            Map ruleMap = new HashMap();
//            ruleMap.put("ruleId", orderMap.get("opxRuleId"));
//            ruleMap.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
//            Map rulesMap = sysconfigFeign.getStoreOpexRule(ruleMap);
////            orderMap.putAll(rulesMap);
//            if (rulesMap == null) {
//                LOGGER.error("{}回执信息处理,优惠规则已删除标志或者不存在,支付单号:{},第三方交易单号：{}",
//                        baseLog,payInfoDO.getId(),dealNo);
//                return true;
//            }
//        }

        //10.设置订单中心消息传递消息体
        Map<String, Object> orderParam = new HashMap<>();
        orderParam.put("orderId", orderMap.get("orderId"));
        //设置积分中心消息传递消息体
//        Map<String, Object> currencyParam = new HashMap<>();
//        if (curNotify) {
//            currencyParam.put("payId", payInfoDO.getId());
//            currencyParam.put("customerId", orderMap.get("customerId"));
//            currencyParam.put("consumptionAmount", orderMap.get("orderPrice"));
//            currencyParam.put("backCurrencyRatio", orderMap.get("backCurrencyRatio"));
//        }
        //设置分账中心消息传递内容
        Map<String, Object> settleParam = new HashMap<>();
        settleParam.put("orderId", orderMap.get("orderId"));
        settleParam.put("outTradeNo", payOrderRelDO.getOutTradeNo());
        settleParam.put("ruleId", orderMap.get("opxRuleId"));
        settleParam.put("totalAmount", payInfoDO.getPayBalance());
        //收银台ID
        settleParam.put("counterId", orderMap.get("counterId"));
        //用户ID
        settleParam.put("customerId", orderMap.get("customerId"));
        //支付分账
        settleParam.put("settleType", "0");
        settleParam.put("payType", payInfoDO.getPayType());
        settleParam.put("payChannel", payInfoDO.getPayChannel());

        try {
            //11. 订单中心
            Message orderMessage = new Message(PayMQConfig.ORDER_TOPIC, PayMQConfig.ORDER_TAG_PAY,
                    JSON.toJSONString(orderParam, SerializerFeature.DisableCircularReferenceDetect).getBytes());
            producer.send(orderMessage);
            LOGGER.info("{}支付单号:{},第三方交易单号：{}，同步发送订单中心执行完成",baseLog,payInfoDO.getId(),dealNo);
        } catch (Exception e) {
            e.printStackTrace();
            //发送不成功的话，稍后重试

        }

//        if (curNotify) {
//            try {
//                //12. 积分中心
//                Message currencyMessage = new Message(PayMQConfig.CURRENCY_TOPIC, PayMQConfig.CURRENCY_TAG_ADD,
//                        JSON.toJSONString(currencyParam, SerializerFeature.DisableCircularReferenceDetect).getBytes());
//                producer.send(currencyMessage);
//                LOGGER.info("{}支付单号:{},第三方交易单号：{}，同步发送积分中心执行完成",baseLog,payInfoDO.getId(),dealNo);
//            } catch (Exception e) {
//                e.printStackTrace();
//                //发送不成功的话，稍后重试
//            }
//        }

        try {
            //13. 分账中心
            Message settleMessage = new Message(PayMQConfig.SETTLE_TOPIC, PayMQConfig.SETTLE_TAG_SPLIT,
                    JSON.toJSONString(settleParam, SerializerFeature.DisableCircularReferenceDetect).getBytes());
            producer.send(settleMessage);
            LOGGER.info("{}支付单号:{},第三方交易单号：{}，同步发送分账中心执行完成",baseLog,payInfoDO.getId(),dealNo);
        } catch (Exception e) {
//                        LOGGER.error("订单号：" + payYsResultDO.getId() + "，银盛内部单号：" + payYsResultDO.getTradeNo() + "，发送分账中心失败");
            e.printStackTrace();
            //发送不成功的话，稍后重试
        }
        return true;
    }

}
